package com.dh.convert.rule.function;

import java.util.Map;
import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.type.AviatorNil;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorRuntimeJavaType;

public class BeanCopyFunction extends AbstractFunction {

	private static Mapper mapper = new DozerBeanMapper();

	@Override
	public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {
		Object srcObject = arg1.getValue(env);
		if (srcObject == null) {
			return AviatorNil.NIL;
		}
		try {
			Object argObject = arg2.getValue(env);
			Object targetObject = AviatorNil.NIL;
			if (argObject.getClass().getSimpleName().equals("String")) {
				Class<?> cls = Class.forName((String) argObject);
				targetObject = mapper.map(srcObject, cls);
			} else {
				mapper.map(srcObject, argObject);
				targetObject = argObject;
			}

			return new AviatorRuntimeJavaType(targetObject);
		} catch (ClassNotFoundException e) {
		}
		return AviatorNil.NIL;
	}

	@Override
	public String getName() {
		return "beanCopy";
	}

}
